import datetime
import sys


from django.shortcuts import render
import utils.custom_utils as utils
from backend import schedule_jobs

sys.path.insert(0, '..')
from mysite import db_config
from utils import functions as f
from utils.functions import is_login
from crontab import  CronTab


@is_login
def rule_list(request):
    """
    检核规则列表
    :param request:
    :return:
    """
    return render(request, "check/rule_list.html", {"source_system": request.GET.get('company'),
                                                    "risk_market_filter": request.GET.get('risk_market'),
                                                    "username": request.session['username']
                                                    }
                  )


@is_login
def rule_edit(request):
    """
    单条检核规则页面
    :param request:
    :return:
    """
    return render(request, "check/rule_edit.html", {"username": request.session['username'],
                                                   "source_system": request.GET.get('company'),
                                                   "id": request.GET.get('id')
                                                   })


@is_login
def rule_execute_manual(request):
    """
    查询检核进度
    :param request:
    :return:
    """
    date = str(datetime.datetime.now().year) + "-" + str(datetime.datetime.now().month) + '-' + str(datetime.datetime.now().day)
    return render(request, "check/rule_exec.html", {"date": date})


@is_login
def show_crontab(request):
    """
    自动检核配置页面
    :param request:
    :return:
    """
    conn = db_config.mysql_connect()
    with conn.cursor() as curs:

        data = []
        sql = f"""SELECT
        b.menu_name name,
        menu_name_en company,
        '' db,
        CAST( a.check_date AS CHAR ) next_runtime,
        'success' STATUS,
        a.version
        FROM hbd_menu b  left join check_result_version a 
             on a.company = b.menu_name_en and  
             a.id = ( SELECT max( id ) FROM check_result_version WHERE company = a.company ) 
        order  by company
        """
        curs.execute(sql)
        jobs = curs.fetchall()
        jobs = utils.arr_to_dictarr(jobs,curs.description)
        job_backend = schedule_jobs.get_jobs()
        for c_job in jobs:
            c_job['backend'] = False
            for b_job in job_backend:
                if b_job['id'] == c_job['company']:
                    c_job['backend'] = True
                    c_job['trigger'] = b_job['trigger']
            data.append(c_job)
    return render(request, "check/crontab.html", {"jobs": data})


@is_login
def blood_analyze(request):
    """血缘分析"""
    return render(request, "check/blood_analyze.html")
